//
//  WBUserAccount.swift
//  XLWB
//
//  Created by MacBook on 16/7/4.
//  Copyright © 2016年 MacBook. All rights reserved.
//

import UIKit
private let accountFile: NSString = "useaccount.json"

//用户账户信息
class WBUserAccount: NSObject {
 
    //访问令牌
    var access_token:String? //= "2.00C9TPVG0_u646cf457ca97f0D8l2H"// = "2.00C9TPVGuOjD9C426957820eDPolNE"
    //用户代号
    var uid: String?
    //access_token的声明州区,单位是s
    //kaifa zhe 5年
    //使用者3天
    var expires_in: TimeInterval = 0 {
    
        didSet {
        
    
            expiresDate = Date(timeIntervalSinceNow: expires_in)
    
        }
    
    }
    
    //过期日期
    var expiresDate: Date?
    
    //用户昵称
    var screen_name: String?
    //用户头像地址
    var avatar_large: String?
    
    override var description: String {
    
        return yy_modelDescription()
    
    }
    
    override init() {
    
        super.init()
        //从磁盘加载保存的文件--字典
        guard let path = accountFile.cz_appendDocumentDir(),
            data = NSData(contentsOfFile: path),
        dict = try? JSONSerialization.jsonObject(with: data as Data, options: []) as? [String: AnyObject] else {
            
            return
        }
        
        //使用字典设置属性值
        yy_modelSet(with: dict ?? [:])
        
        //判断token是否过期
//         expiresDate = Date(timeIntervalSinceNow: -3600 * 24)
        if expiresDate?.compare(Date()) != .orderedDescending {
            
            print("账户过期")
            access_token = nil
            uid = nil
            
            //删除账户文件
           _ = try? FileManager.default.removeItem(atPath: path)
        }
    }
    /*
     数据存储的几种方式:
     1.偏好设置xcode8 beta 无效
     2.沙盒 - 归档 
     3.数据库
     4.钥匙串访问(自动加密/小)
     */
    
    func saveAccount() {
    
       //1.模型转字典
        var dict = (self.yy_modelToJSONObject() as? [String
            : AnyObject]) ?? [:]
        //需要删除expires_in 值
        dict.removeValue(forKey: "expires_in")
        
        //字典序列化
        guard let data = try? JSONSerialization.data(withJSONObject: dict, options: []),
            filePath = ("useaccount.json" as NSString).cz_appendDocumentDir() else {
            return
        }
    
        // 写入磁盘
        (data as NSData).write(toFile: filePath, atomically: true)
        
        print("用户账户保存成功 \(filePath)")
        
    
    }
}
